
const GET = 'GET';
const POST = 'POST';
const PUT = 'PUT';
const FORM = 'FORM';
const DELETE = 'DELETE';

// const baseURL = 'https://some-domain.com/api/';
const baseURL = 'http://127.0.0.1:8000/api/v1/';

function request(method, url, data, handle) {
  return new Promise(function (resolve, reject) {
    let header = {
      'content-type': 'application/json',
    };
    wx.showLoading({
      title: '加载中',
    })
    // 保证传出空对象
    if (!data)  data={}
    // data = JSON.stringify(data)
    console.log('requeset data ',data)

    wx.request({
      url: baseURL + url,
      method: method,
      // data: method === POST ? JSON.stringify(data) : data,
      data: data,
      header: header,
      success(res) {
        //请求成功
        if (handle) {
          // 自定义处理
          if (handle(res)) {
            resolve(res.data.data)
          } else {
            reject('请求失败，请稍后重试')
          }
          return
        }
        //判断状态码---errCode状态根据后端定义来判断
        if (res.statusCode != 200) {
          wx.showToast({
            title: res.data.msg ? res.data.msg : "网络异常请稍后重试",
            icon: 'none',
          })
          console.log("request fail :", res)
          reject('请求失败,请稍后再试');
        } else {
          //成功
          resolve(res.data.data);
        }
      },
      fail(err) {
        //请求失败
        console.log("request fail :", res)
        reject(err)
      },
      complete() {
        wx.hideLoading()
      }
    })
  })
}

const API = {
  getOpenid: (data) => request(GET, `jsapi/mini?jsCode=${data}`),
  getToken: (data) => request(POST, `token`,data),
  login: (data) => request(POST, `login`,data),
  // 除登录和 token外 任何方法都要附加token
  malfunctionList: (data,token) => request(POST, `malfunctions?token=${token}&_method=get`,data),
  addMalfunction: (data,token) => request(POST, `malfunctions?token=${token}&_method=add`,data),
  updateMalfunction: (data,token,id) => request(PUT, `malfunctions/${id}?token=${token}`,data),
  deleteMalfunction: (data,token) => request(DELETE, `malfunctions?token=${token}`,data),

  userRent: (data,token, handle) => request(POST, `user_rent?token=${token}`,data, handle),
  addRent: (data,token) => request(POST, `rents?token=${token}`,data),
  deleteRent: (data,token,id) => request(DELETE, `rents/${id}?token=${token}`,data),

  roomList: (data,token) => request(POST, `rooms?token=${token}&_method=get`,data)
};
module.exports = {
  API: API
}